#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from typing import List

from utils.logoperator import LogOperator

logger = LogOperator(__name__, isprint=False)


class AdbOperator:
    def __init__(self, device_id=None, adb_path=None):
        self._adb_path = adb_path or "adb"
        self._device_id = device_id

    @property
    def device_id(self):
        if self._device_id is None:
            self._device_id = self.list_device()[0]
        return self._device_id

    @staticmethod
    def list_device() -> List:
        proc = subprocess.Popen("adb devices", stdout=subprocess.PIPE, shell=True)
        result = proc.stdout.read()
        if not isinstance(result, str):
            result = result.decode('utf-8')
        result = result.replace('\r', '').splitlines()
        logger.debug(f"adb devices:{result}")
        device_list = []
        for device in result[1:]:
            if len(device) <= 1 or not '\t' in device: continue
            if device.split('\t')[1] == 'device':
                device_list.append(device.split('\t')[0])
        return device_list

    def _run_cmd_once(self, cmd, *argv):
        if self.device_id:
            cmdlet = [self._adb_path, '-s', self.device_id, cmd]
        else:
            cmdlet = [self._adb_path, cmd]
        for i in range(len(argv)):
            arg = argv[i]
            if not isinstance(argv[i], str):
                arg = arg.decode('utf8')
            cmdlet.append(arg)
        cmd_str = " ".join(cmdlet)
        logger.debug(f'执行的语句为{cmd_str}')
        process = subprocess.Popen(cmd_str, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                   shell=True)
        (out, error) = process.communicate()
        if not isinstance(out, str):
            out = out.decode('utf-8')
        return out.strip()

    def run_adb_cmd(self, cmd, *argv, **kwds):
        retry_count = 3
        ret = ""
        if "retry_count" in kwds:
            retry_count = kwds['retry_count']
        for i in range(retry_count):
            ret = self._run_cmd_once(cmd, *argv, **kwds)
            if ret is not None:
                break
        return ret

    def run_shell_cmd(self, cmd, **kwds):
        ret = self.run_adb_cmd('shell', '%s' % cmd, **kwds)
        if ret is None:
            logger.error(f'执行「{cmd}」异常')
        return ret

    def get_device_language(self):
        return self.run_shell_cmd("settings get system system_locales")

    def clear_app_data(self, package_name):
        return self.run_adb_cmd("shell pm clear %s" % package_name)
